<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%String path = request.getContextPath();%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>优惠券管理 修改</title>
<jsp:include page="../../import.jsp" flush="true"/>

<style>
  .blockBox {
    float: none !important;
    margin-bottom: 10px;
  }
  .field-option {
    line-height: 20px;
    vertical-align:top;
    margin-bottom: 8px;
  }
  .field-option .l-text-wrapper {
    display: inline-block;
    vertical-align:top;
  }
  .field-option .l-radio-wrapper {
    vertical-align:top;
  }
</style>
<script>
var _cpId = ${cpId};
var _couponDetail = {} 
var manager, g;
const _ruleList = [
  {
    cpId: '',
    priority: 1,
    discountDays: '',
    discountDaysMin: '',
    discountAmtMax: ''
  },
  {
    cpId: '',
    priority: 2,
    discountDays: '',
    discountDaysMin: '',
    discountAmtMax: ''
  },
  {
    cpId: '',
    priority: 3,
    discountDays: '',
    discountDaysMin: '',
    discountAmtMax: ''
  },
  {
    cpId: '',
    priority: 4,
    discountDays: '',
    discountDaysMin: '',
    discountAmtMax: ''
  }
];
getCouponDetail();
function getCouponDetail () {
  var url = '<%=path%>/mcr/mcrCouponMain/getById.do?cpId='+ _cpId
  console.log(url)
  $.ajax({
    async: false,
    type: 'get',
    url: url,
    success: function (msg) {
      msg = JSON.parse(msg)
      if (msg.success == 1) {
        _couponDetail = msg.data
        _ruleList.forEach(item => {
          var rule = _couponDetail.ruleList.find(r => r.priority == item.priority)
          if (rule) {
            Object.assign(item, rule)
          }
        })
      }
    }
  });
}

function initForm () {
  $('#cpNm').val(_couponDetail.cpNm)
  _couponDetail.payType = _couponDetail.payType.replace(',', ';')
  liger.get("payType").selectValue(_couponDetail.payType);
  liger.get("discountType").selectValue(_couponDetail.discountType);
  liger.get("cstType").selectValue(_couponDetail.cstType);
  liger.get("useNode").selectValue(_couponDetail.useNode);
  liger.get("loanType").selectValue(_couponDetail.loanType);
  liger.get("displayType").selectValue(_couponDetail.displayType);
  liger.get("cpType").selectValue(_couponDetail.cpType);
  liger.get("cpType").selectValue(_couponDetail.cpType);
  var expireType = _couponDetail.expireType
  var expireTypeId = '#expireType_'
  if (expireType === 'FIXED_PERIOD') {
    expireTypeId += '0'
    $("#strDate").ligerGetDateEditorManager().setValue(_couponDetail.strDate);
    $("#endDate").ligerGetDateEditorManager().setValue(_couponDetail.endDate);
  } else if (expireType === 'FIXED_DAYS') {
    $("#fixedDays").val(_couponDetail.fixedDays)
    expireTypeId += '1'
  } else {
    expireTypeId += '2'
  }
  var perLimit = _couponDetail.perLimit == '0' ? 0 : 1
  
  if (perLimit == 1) {
    $("#perLimitValue").val(_couponDetail.perLimit)
  }
  $('#instruction').val(_couponDetail.instruction)
  $("#perLimit_0").attr("checked", true);
  $(expireTypeId).attr("checked", true);
}

$(function() {
  // 判断有效期-开始时间
  function strDateChange() {
    var strDate_val=$("#strDate").val();
    var strDate_base=$("#strDate_base").val();
    var endDate_base=$("#endDate_base").val();
    if(strDate_val==strDate_base){
      return false;
    }
    if(strDate_val < endDate_base){
      $.ligerDialog.SQalert({content: "新有效期开始时间应大于原有效期结束时间！",SQ_type: "warning"});
      $("#strDate").val("");
      $("#isBegin").val("0");
    }else{
      $("#isBegin").val("1");
    }
  }
  // 判断有效期-结束时间
  function endDateChange() {
    var endDate_val=$("#endDate").val();
    var strDate_val=$("#strDate").val();
    var endDate_base=$("#endDate_base").val();
    if(endDate_val==endDate_base){
      return false;
    }
    if(endDate_val < strDate_val){
      $.ligerDialog.SQalert({content: "有效期结束时间应大于有效期开始时间！",SQ_type: "warning"});
      $("#endDate").val("");
      $("#isEnd").val("0");
    }else{
      $("#isEnd").val("1");
    }
  }
  // 还款类型多选框
  $("#payType").ligerComboBox({
    data: [
      {
        key: '正常还款',
        value: 'NORMAL'
      },
      {
        key: '提前结清',
        value: 'EARLIER_SETTLE'
      }
    ],
    valueFieldID : 'value',
    valueField: 'value',
    textField: 'key',
    isMultiSelect: true,
    isShowCheckBox: true ,
  });

  $("#discountType").ligerComboBox({
    data: [
      {
        key: '应还利息',
        value: 'INTEREST_PAYABLE'
      }
    ],
    textField: 'key',
    valueFieldID : 'value',
    valueField: 'value'
  })
  liger.get("discountType").selectValue("NORMAL");

  $("#cstType").ligerComboBox({
    data: [
      {
        key: '内部用户',
        value: 0
      }
    ],
    textField: 'key',
    valueFieldID : 'value',
    valueField: 'value'
  })

  $("#useNode").ligerComboBox({
    data: [
      {
        key: '用信',
        value: 'APPLY_LOAN'
      }
    ],
    textField: 'key',
    valueFieldID : 'value',
    valueField: 'value'
  })

  $("#loanType").ligerComboBox({
    data: [
      {
        key: '随借随还',
        value: 'SJSH'
      }
    ],
    textField: 'key',
    valueFieldID : 'value',
    valueField: 'value'
  })

  $("#displayType").ligerComboBox({
    data: [
      {
        key: '最高金额',
        value: 'MAX_AMT'
      },
      {
        key: '最大天数',
        value: 'MAX_DAYS'
      }
    ],
    valueFieldID : 'value',
    valueField: 'value',
    textField: 'key'
  })

  $("#cpType").ligerComboBox({
    data: [
      {
        key: '减息券',
        value: 1
      }
    ],
    textField: 'key',
    valueFieldID : 'value',
    valueField: 'value'
  });

  // $('#expireType_0').ligerRadio();
  // $('#expireType_1').ligerRadio();
  // $('#expireType_2').ligerRadio();

  // $('#perLimit_0').ligerRadio();
  // $('#perLimit_1').ligerRadio();

  $("#strDate").ligerDateEditor({
    onChangeDate: function (value) {
      strDateChange();
    }
  });
  $("#endDate").ligerDateEditor({
    onChangeDate: function (value) {
      endDateChange();
    }
  });


  /** 处理优惠券规则 **/
  $(f_initGrid);
  function f_initGrid () {
    g = manager = $("#maingrid").ligerGrid({
      columns: [
        {
          display: '#',
          render: function (rowdata, rowindex, value) {
            return '第'+ rowdata.priority +'优先级'
          }
        },
        {
          display: '优惠天数',
          name: 'discountDays',
          width: 70,
          editor: { type: 'number' }
        },
        {
          display: '最短使用天数限制',
          name: 'discountDaysMin',
          editor: { type: 'number' }
        },
        {
          display: '优惠上限（元）',
          name: 'discountAmtMax',
          editor: { type: 'number' }
        },
        {
          display: '操作',
          isSort: false,
          render: function (rowdata, rowindex, value) {
            var h = "";
            if (!rowdata._editing) {
              h += "<a class='beginEdit' index=" + rowindex + ">修改</a> ";
            } else {
              h += "<a class='endEdit' index=" + rowindex + ">确认</a> ";
              h += "<a class='cancelEdit' index=" + rowindex + ">取消</a> "; 
            }
            return h;
          }
        }
      ],
      enabledEdit: true,
      clickToEdit: false,
      isScroll: false,
      data: { Rows: _ruleList },
      usePager: false,
      width: '100%'
    })

  }
  $('#maingrid').on('click', '.beginEdit',function (e) {
    var index = $(e.target).attr('index')
    manager.beginEdit(index)

  })
  $('#maingrid').on('click', '.endEdit',function (e) {
    var index = $(e.target).attr('index')
    manager.endEdit(index)
  })
  $('#maingrid').on('click', '.cancelEdit',function (e) {
    var index = $(e.target).attr('index')
    manager.cancelEdit(index)
  })
  /** 处理优惠券规则 **/  

  initForm()
})
</script>
</head>
<body class="iframeBody">
  <div class="Wrapper">
    <div class="fieldset1 tabel_col clearFix">
      <div class="caption">
        <span class="title">优惠券规则设置</span>
      </div>
    </div>
    <form id="formSet1">
      <div class="fieldset1 clearFix">

        <div class="FXBR">
          <div class="fieldBox blockBox clearFix">
            <span class="label">
              优惠券名称
              <span class="requiredSymbol">*</span>
            </span>
            <span class="field">
              <input name="cpNm" id="cpNm" type="text" class="ui-textbox" value="" ligerui="width: 160">
            </span>
          </div>
          <div class="fieldBox  blockBox clearFix">
            <div class="label">
              优惠券类型
              <span class="requiredSymbol">*</span>
            </div>
            <div class="field">
              <input type="text" name="cpType" id="cpType" placeholder="请选择">
            </div>
          </div>
          <div class="fieldBox  blockBox clearFix">
            <span class="label" style="float: none;">
              规则设置
              <span class="requiredSymbol">*</span>
            </span>
            <div style="margin-left: 70px; margin-top: -20px;">
              说明：优惠券会默认触发最高优先级优惠方案，其中第一优先级必填，任一优先级任一空格有内容则所有空格必填，例如;
              <br>
              优先级1填写优惠3天，天数限制10天，上限100元;
              <br>
              优先级2填写优惠1天，天数限制5天，上限50元.
              <br>
              则用户借款
              <br>
              4天还款，不触发优惠劵；
              <br>
              6天还款触发优先级2；
              <br>
              10天还款触发优先级1

              <div id="maingrid">
              </div>
            </div>
          </div>

          <div class="fieldBox  blockBox clearFix">
            <div class="label">
              适用还款类型
              <span class="requiredSymbol">*</span>
            </div>
            <div class="field">
              <input type="text"name="payType" id="payType" placeholder="请选择">
              
              <!-- <option value="NORMAL" checked >正常还款</option>
              <option value="" checked >逾期还款</option>
              <option value="" checked >提前还款</option>
              <option value="" checked >正常结清</option>
              <option value="" checked >提前结清</option> -->
            </div>
          </div>

          <div class="fieldBox  blockBox clearFix">
            <div class="label">
              计算金额
              <span class="requiredSymbol">*</span>
            </div>
            <div class="field">
              <input type="text" name="discountType" id="discountType" placeholder="请选择">
            </div>
          </div>

          <div class="fieldBox  blockBox clearFix">
            <div class="label">
              优惠券有效期
              <span class="requiredSymbol">*</span>
            </div>
            <div class="field">
              <p class="field-option">
                <input type="radio" name="expireType" id="expireType_0" value="FIXED_PERIOD">
                固定时间
                <input style="margin-left: 20px;" name="strDate" id="strDate" type="text" class="ui-datepicker" value="" validate="{required:true}" style="display: inline-block">
                <span>---</span>
                <input name="endDate" id="endDate" type="text" class="ui-datepicker" value="" validate="{required:true}" style="display: inline-block">
                <span class="requiredSymbol">*</span>
              </p>
              <p class="field-option">
                <input type="radio" name="expireType" id="expireType_1" value="FIXED_DAYS"/>
                固定天数
                <input name="fixedDays" id="fixedDays" class="ui-textbox" type="number" value="" ligerui="width: 160">
              </p>
              <p class="field-option">
                <input type="radio" name="expireType" id="expireType_2" value="LONG_LONG" />
                长期有效
              </p>
            </div>
          </div>

          <div class="fieldBox blockBox clearFix">
            <span class="label">
              使用说明
            </span>
            <span class="field">
              <textarea id="instruction"  name="instruction" rows="3" class="l-textarea" style="width:360px; height: 68px;"></textarea>
            </span>
          </div>
        </div>
      </div>
    </form>
    
    <div class="fieldset1 tabel_col clearFix">
      <div class="caption">
        <span class="title">发放设置</span>
      </div>
    </div>

    <form id="formSet2">
      <div class="fieldset1 clearFix">

        <div class="FXBR">
          <div class="fieldBox blockBox clearFix">
            <span class="label">
              适用客户类型
              <span class="requiredSymbol">*</span>
            </span>
            <span class="field">
              <div class="field">
                <input type="text" name="cstType" id="cstType" placeholder="请选择">
              </div>
            </span>
          </div>
          <div class="fieldBox  blockBox clearFix">
            <div class="label">
              使用节点
              <span class="requiredSymbol">*</span>
            </div>
            <div class="field">
              <input type="text" name="useNode" id="useNode" placeholder="请选择">
            </div>
          </div>

          <div class="fieldBox  blockBox clearFix">
            <div class="label">
              适用还款类型
              <span class="requiredSymbol">*</span>
            </div>
            <div class="field">
              <input type="text" name="loanType" id="loanType" placeholder="请选择">
            </div>
          </div>

          <div class="fieldBox  blockBox clearFix">
            <div class="label">
              每个人限发
              <span class="requiredSymbol">*</span>
            </div>
            <div class="field">
              <!-- <p class="field-option">
                <input type="radio" name="perLimit" id="perLimit_0" value="0">
                不限
              </p> -->
              <p class="field-option">
                <input type="radio" name="perLimit" id="perLimit_1" value="1">
                限
                <input style="margin-left: 20px;" name="perLimit" id="perLimitValue" type="text" class="ui-textbox" value="" ligerui="width: 160">
              </p>
            </div>
          </div>

          <!-- <div class="fieldBox  blockBox clearFix">
            <div class="label">
              是否系统发放目标客户
              <span class="requiredSymbol">*</span>
            </div>
            <div class="field">
              <p class="field-option">
                <input type="radio" name="issueType" id="issueType_0" value="1">
                是
                <select style="margin-left: 20px;" name="issueTypeCd" id="issueTypeCd" data-value=" ">
                  <option value=" " checked >--请选择--</option>
                  <option value="NEW" checked >新用户</option>
                </select>
              </p>
              <p class="field-option">
                <input type="radio" name="issueType" id="issueType_1" value="0">
                否
                <span style="margin-left: 20px;">请配置发放名单</span>
              </p>
            </div>
          </div> -->
          <div class="fieldBox blockBox clearFix">
            <span class="label">
              展示效果设置
            </span>
          </div>
          <div class="fieldBox blockBox clearFix">
            <span class="label">
              优惠券展示
              <span class="requiredSymbol">*</span>
            </span>
            <span class="field">
              <input type="text" name="displayType" id="displayType" placeholder="请选择">
            </span>
          </div>
        </div>
      </div>
    </form>
  </div>
</body>
<script>
//定义父级调用事件
frameElement.dialog.onOk = function () {
  save();
}
frameElement.dialog.onCancel = function () {
  frameElement.dialog.close();
}
function validatorList () {
  var ruleList = manager.getData();
  // 校验填写优惠券规则
  ruleList = ruleList.filter(function (item) {
    return item.discountDays !== '' && item.discountDaysMin !== '' && item.discountAmtMax !== '' 
    ''  
  });
  if (ruleList.length == 0) {
    alert('请填写优惠券规则')
    $.ligerDialog.SQalert({
      content: '请填写优惠券规则',
      SQ_type: "warning"
    });
    return false
  }

  // 校验每级优惠券填写完整性
  var unrule = ruleList.find(function (item) {
    return (item.discountDays === '') || (item.discountDaysMin === '' ) || (item.discountAmtMax === '')
  });
  if (unrule) {
    $.ligerDialog.SQalert({
      content: '请填将第'+ unrule.priority +'优先级规则填写完成',
      SQ_type: "warning"
    });
    return false
  }
  return ruleList
}
function validator (str, msg, type) {
  var val;
  if (type) {
    val = $(str).ligerComboBox().selectedValue
  } else {
    val = $(str).val()
  }
  if (!val || val === '') {
    $.ligerDialog.SQalert({
      content: msg,
      SQ_type: "warning"
    });
    return false
  }
  return val
}
function getInputInfo () {
  var data = {}
  // 优惠券规则设置 名称
  var cpNm = validator('#cpNm', '优惠券名称不能为空')
  if (!cpNm) {
    return
  }
  data.cpNm = cpNm;

  // 优惠券类型
  var cpType = validator('#cpType', '优惠券类型不能为空', 1)
  if (!cpType) {
    return
  }
  data.cpType = cpType;

  var payType = validator('#payType', '适用还款类型不能为空', 1)
  if (!payType) {
    return
  }
  data.payType = payType.replace(';', ',');

  var discountType = validator('#discountType', '计算金额不能为空', 1)
  if (!discountType) {
    return
  }
  data.discountType = discountType;

  var expireType = validator('input[name="expireType"]:checked', '优惠券有效期不能为空')
  if (!expireType) {
    return
  }
  data.expireType  = expireType;

  if (expireType === 'FIXED_PERIOD') {
    var strDate = validator('#strDate', '优惠券有效期为固定时间，开始时间不能为空')
    var endDate = validator('#endDate', '优惠券有效期为固定时间，结束时间不能为空')
    if (!strDate || !endDate) {
      return
    }
    data.strDate = strDate;
    data.endDate = endDate;
  } else if (expireType === 'FIXED_DAYS') {
    var fixedDays = $('#fixedDays').val();
    var fixedDays = validator('#fixedDays', '优惠券有效期为固定天数，天数不能为空')
    if (!fixedDays) {
      return
    }
    data.fixedDays = fixedDays;
  }

  var instruction = $('#instruction').val();
  data.instruction = instruction;

  // 获取优惠券规则
  var ruleList = validatorList();
  if (!ruleList) {
    return
  }
  data.ruleList = ruleList;

  // 发放设置
  var cstType = validator('#cstType', '适用客户类型不能为空', 1)
  if (!cstType) {
    return
  }
  data.cstType = +cstType;

  var useNode = validator('#useNode', '使用节点不能为空', 1)
  if (!useNode) {
    return
  }
  data.useNode = useNode;

  var loanType = validator('#loanType', '适用还款类型不能为空', 1)
  if (!loanType) {
    return
  }
  data.loanType = loanType;

  var perLimit = validator("input[name='perLimit']:checked", '每个人限发不能为空')
  if (!perLimit) {
    return
  }
  if (perLimit == 1) {
    perLimit = validator('#perLimitValue', '每个人限发限制时，限制次数不能为空')
    if (!perLimit) {
      return
    }
  }
  data.perLimit = +perLimit;

  var displayType = validator('#displayType', '优惠券展示不能为空', 1)
  if (!displayType) {
    return
  }
  data.displayType = displayType;
  data.issueType = 0
  // 设置优惠券状态
  return data
}

function save () {
  var data = getInputInfo()
  if (!data) {
    return false
  }
  console.log(data)
  var wait_dialog;
  $.ajax({
    type: 'post',
    data: JSON.stringify(data),
    dataType : 'json',
    contentType: 'application/json',
    processData: false,
    url: '<%=path%>/mcr/mcrCouponMain/modify.do',
    beforeSend: function(){
      wait_dialog = $.ligerDialog.SQalert({
        content: LogUtils.LOG_CMM_DATA_LOADING,
        SQ_type: "waitting"
      });
    },
    success:function (msg) {
      console.log(msg)
      wait_dialog.close();
      if(msg.success == 1){
        $.ligerDialog.SQalert({content:msg.info, SQ_type: "success"});
        frameElement.dialog.close();
      }else{
        $.ligerDialog.SQalert({content:msg.info, SQ_type: "error"});
      }
    }
  });
}

//定义父级调用事件
frameElement.dialog.onOk = function () {
  save();
}
frameElement.dialog.onCancel = function () {
  frameElement.dialog.close();
}
</script>
</html>
